package com.weyoung.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weyoung.app.mapper.UserMapper;
import com.weyoung.app.pojo.dto.req.UserLoginReqDTO;
import com.weyoung.app.pojo.dto.req.UserUpdateReqDTO;
import com.weyoung.app.pojo.dto.resp.UserDetailRespDTO;
import com.weyoung.app.pojo.dto.resp.UserLoginRespDTO;
import com.weyoung.app.pojo.entity.User;
import com.weyoung.app.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 用户实体的 Service 实现类，继承自 ServiceImpl 并实现 UserService 接口
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    private final UserMapper userMapper;

    @Override
    public UserDetailRespDTO WXLogin(String openid, String nickname, String avatarUrl) {
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getOpenid, openid));
        if (user == null) {
            // 用户不存在，新增用户
            String username = generateUniqueUsername(openid);
            user = new User();
            user.setOpenid(openid);
            user.setUsername(username);
            if (StrUtil.isBlank(nickname)) {
                user.setNickname(username);
            } else {
                user.setNickname(nickname);
            }
            if (StrUtil.isBlank(avatarUrl)) {
                user.setAvatarUrl("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=4212546809,2253368881&fm=253&gp=0.jpg");
            } else {
                user.setAvatarUrl(avatarUrl);
            }
            baseMapper.insert(user);
        }
        StpUtil.login(user.getOpenid());
        String token = StpUtil.getTokenValue();
        return getUserDetail();
    }

    @Override
    public UserDetailRespDTO login(UserLoginReqDTO requestParam) {
        if (StrUtil.isBlank(requestParam.getUsername()) || StrUtil.isBlank(requestParam.getPassword())) {
            throw new RuntimeException("用户名或密码不能为空");
        }
        // 修正 eq 方法调用，添加字段参数 User::getUsername
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, requestParam.getUsername()));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 校验密码是否正确
        if (!user.getPassword().equals(requestParam.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        // 登录成功后生成 token
        StpUtil.login(user.getOpenid());
        String token = StpUtil.getTokenValue();
        // 返回登录响应对象
        return getUserDetail();
    }

    @Override
    public UserDetailRespDTO update(UserUpdateReqDTO requestPram) {
        String openID = StpUtil.getLoginId().toString();
        if (StrUtil.isBlank(openID)) {
            throw new RuntimeException("用户未登录");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", requestPram.getId());
        updateWrapper.eq("openid", openID);

        if (StrUtil.isNotEmpty(requestPram.getUsername())) {
            updateWrapper.set("username", requestPram.getUsername());
        }
               if (StrUtil.isNotEmpty(requestPram.getPassword())) {
            updateWrapper.set("password", requestPram.getPassword());
        }
        if (StrUtil.isNotEmpty(requestPram.getNickname())) {
            updateWrapper.set("nickname", requestPram.getNickname());
        }
        if (StrUtil.isNotEmpty(requestPram.getAvatarUrl())) {
            updateWrapper.set("avatar_url", requestPram.getAvatarUrl());
        }
        if (requestPram.getGender() != null && requestPram.getGender() != 0) {
            updateWrapper.set("gender", requestPram.getGender());
        }
        if (StrUtil.isNotEmpty(requestPram.getCity())) {
            updateWrapper.set("city", requestPram.getCity());
        }
        if (StrUtil.isNotEmpty(requestPram.getProvince())) {
            updateWrapper.set("province", requestPram.getProvince());
        }
        if (StrUtil.isNotEmpty(requestPram.getCountry())) {
            updateWrapper.set("country", requestPram.getCountry());
        }
        if (StrUtil.isNotEmpty(requestPram.getPhone())) {
            updateWrapper.set("phone_number", requestPram.getPhone());
        }
        if (StrUtil.isNotEmpty(requestPram.getEmail())) {
            updateWrapper.set("email", requestPram.getEmail());
        }
        if (requestPram.getHeight() != null && requestPram.getHeight() != 0) {
            updateWrapper.set("height", requestPram.getHeight());
        }
        if (requestPram.getWeight() != null && requestPram.getWeight() != 0) {
            updateWrapper.set("weight", requestPram.getWeight());
        }
        if (requestPram.getBirthDay() != null) {
            updateWrapper.set("birthday", requestPram.getBirthDay());
        }
        if (StrUtil.isNotEmpty(requestPram.getBloodType())) {
            updateWrapper.set("blood_type", requestPram.getBloodType());
        }

        int update = userMapper.update(null, updateWrapper);
        if (update < 0) {
            throw new RuntimeException("更新失败");
        }
        return getUserDetail();
    }


    @Override
    public UserDetailRespDTO getUserDetail() {
        String openID = StpUtil.getLoginId().toString();
        if (StrUtil.isBlank(openID)) {
            throw new RuntimeException("用户未登录");
        }
        String tokenValue = StpUtil.getTokenValue();
        User user = baseMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getOpenid, openID));

        return UserDetailRespDTO.builder()
                .id(user.getId())
                .token(tokenValue)
               .username(user.getUsername())
               .nickname(user.getNickname())
               .avatarUrl(user.getAvatarUrl())
               .gender(user.getGender())
               .city(user.getCity())
               .province(user.getProvince())
               .country(user.getCountry())
               .phone(user.getPhone())
               .email(user.getEmail())
               .height(user.getHeight())
               .weight(user.getWeight())
               .birthDay(user.getBirthDay())
               .bloodType(user.getBloodType())
               .build();
    }



    /**
     * 生成唯一的用户名
     *
     * @param openid 微信openid
     * @return 用户名
     */
    private String generateUniqueUsername(String openid) {
        String baseUsername = "user_" + openid.substring(0, 8); // 基于openid生成基础用户名
        String username = baseUsername;
        int counter = 1;
        while (userMapper.exists(Wrappers.<User>lambdaQuery().eq(User::getUsername, username))) {
            username = baseUsername + "_" + counter;
            counter++;
        }
        return username;
    }
}
